package ajaxjs.net.upload;

import java.io.File;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import ajaxjs.Fso;
import ajaxjs.Constant;
/**
 * 
 * <body>
   <form action="upload2.jsp" enctype="multipart/form-data" method="POST" >
      selectimage: <input type="file" name="myfile"/><br>
      <input type="submit" value="upload"/>
   </form>
</body>

com.ajaxjs.bigfoot.net.Upload uploader = new com.ajaxjs.bigfoot.net.Upload();
com.ajaxjs.bigfoot.net.Upload.req = request;
uploader.setSaveFolder("\\img\\");
String fileName = uploader.upload();
out.write(fileName);
 * @author Administrator
 *
 */
public class Upload_HTTP extends BaseUpload{
	public Upload_HTTP(HttpServletRequest request) {
		super(request);
	}
	public int MAX_SIZE = 2024000000;
	public String upload(){
		String errCode = "";
		if(!request.getMethod().equals("POST")){
			errCode += "应使用 POST 方法上传！";
		}

		if(request.getContentType().indexOf("multipart/form-data") < 0){
			errCode += " 未找到上传文件！";
		}
		
	    if(request.getContentLength() > MAX_SIZE){
	    	errCode += " 文件大小超过系统限制！";
	    } 
	    
	    if(errCode.equals(""))
	    	return super.upload();
	    else{
	    	request.setAttribute(Constant.json_Err_KeyName, errCode.trim());
	    	return null;
	    }
	}
	
	/**
	 * 是否保存在服务器目录上，如果是，外界可以通过 HTTP 访问；如果不是，则是一个绝对的磁盘文件路径。
	 */
	public boolean isSaveOnServer = true; 
	public String saveFolder = "";
 
	/**
	 * 设置保存文件的目录
	 * @return
	 */
	public void setSaveFolder(String saveFolder){
		if(isSaveOnServer){
			this.saveFolder = ajaxjs.net.Request.Mappath(request, saveFolder);
		}else{
			this.saveFolder = saveFolder;
		}
		
		this.saveFolder += File.separator;
//	    String  rootPath,
//	    realPath = request.getServletContext().getRealPath("/");
//	    
////		realPath = realPath.substring(0, realPath.lastIndexOf("\\"));	// win32
////	    realPath = realPath.substring(0, realPath.lastIndexOf("/"));	// linux
//	    realPath = realPath.substring(0, realPath.lastIndexOf(File.separator));
//		rootPath = realPath + saveFolder;
//		
//		return rootPath;
	}
	public boolean isOverwriteExistFile = true;
	/**
	 * 是否上传后改名为日期
	 */
	public boolean isNameByDate = true;
	public String fileName = "";
	
	/**
	 * 取得上传的文件名
	 * @param data
	 * @return
	 */
	public void setFileName(String data){
		fileName = data.substring(data.indexOf("filename=\"") + 10);
		fileName = fileName.substring(0, fileName.indexOf("\n"));
		fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.indexOf("\""));
		
		if(isNameByDate){
			String [] arr = fileName.split("\\.");
			String extName;
			if(arr != null && arr.length > 0){
				extName = "." + arr[arr.length - 1];
			}else{
				extName = ""; // 没有扩展名
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  // 文件上传时生成“日期+1970 毫秒数”
			fileName = sdf.format(new java.util.Date());
			fileName += "_" + System.currentTimeMillis() + extName;
		}
	}
	
	/**
	 * 创建磁盘文件
	 * @param rootPath
	 * @param saveFile
	 * @param dateBytes
	 * @param startPos
	 * @param endPos
	 * @return
	 * @throws Exception
	 */
	public String createFile(byte[] dateBytes, int startPos, int offsetPos){
		String fileData = super.createFile(dateBytes);
		setFileName(fileData);
		
		fileName = fileName.replace("\\", "/");
		
		File checkFile = new File(fileName);
	    if(!isOverwriteExistFile  && checkFile.exists()){
	        System.out.println("文件已经存在！");
	        return "文件已经存在！";
	    }
	    
	    File fileDir = new File(saveFolder);
	    if(!fileDir.exists())fileDir.mkdirs(); // 如目录不存在则创建目录
	    
	    // 写入文件
	    String fullFileName = saveFolder + fileName;
		Fso.writeFile(fullFileName, dateBytes, startPos, offsetPos);
		System.out.println("上传成功：" + fullFileName);
		
	    return fullFileName;
	}
}